package org.zlm.git_study.aspect;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.zlm.git_study.pojo.User;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * @author zlm
 * @date 2023/12/20
 */
@Aspect
@Component
@RequiredArgsConstructor
public class IdAutoGenAspect {

    private final SnowflakeGenerator snowflakeGenerator;

    @Pointcut("execution(* org.zlm.git_study.controller.*Controller.save(..)) && args(org.zlm.git_study.pojo.User)")
    public void pointcut(){
    }

    @Before("execution(* org.zlm.git_study.controller.*Controller.save(..)) && args(user)")
    public void autoGenId(User user){
        Field[] fields = user.getClass().getDeclaredFields();
        Arrays.stream(fields).forEach(field -> {
            field.setAccessible(true);
            try {
                if(field.getName().equals("id")){
                    String id = snowflakeGenerator.next().toString();
                    System.out.println(id.length());
                    field.set(user, id);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });

    }
//    @Before("pintcut()")
//    public void autoGenId(JoinPoint joinPoint){
//        String methodName = joinPoint.getSignature().getName();
//        Object[] args = joinPoint.getArgs();
//        if(args[0] instanceof User){
//            User user = (User) args[0];
//            user.setId("1234");
//        }
//        System.out.println("after() methodName:" + methodName + ", args:" + Arrays.toString(args));
//
//    }
}
